package com.softaria.windows.logic;

import java.util.HashMap;

import com.softaria.windows.model.ModelUrl;
import com.softaria.windows.widgets.HelpPanel;

/**
 * This class contains logic of switching help message when active view or
 * perspective changes. It is used internally by {@link WindowsManager}
 * 
 * @author Roman M Kuzmin (roman@softaria.com)
 * @see WindowsManager
 * 
 */
class HelpManager {

  private class Messages {

    public Messages(String title, String text) {
      super();
      this._text = text;
      this._title = title;
    }

    private String _title;
    private String _text;

    public String getTitle() {
      return _title == null ? "" : _title;
    }

    public String getText() {
      return _text == null ? "" : _text;
    }

  }

  /**
   * Target for help messages
   */
  private HelpPanel helpPanel;

  /**
   * Current active view or perspective
   */
  private ModelUrl activeAuthor;

  /**
   * current texts for all views and perspectives
   */
  private HashMap<ModelUrl, Messages> helpMessages = new HashMap<ModelUrl, Messages>();

  public HelpManager(HelpPanel helpPanel) {
    super();
    this.helpPanel = helpPanel;
  }

  /**
   * Part of public API. Sets new help message
   * 
   * @param author
   *          - author of message
   * @param message
   */
  public void setHelpMessage(ModelUrl author, String title, String message) {
    if (message == null) {
      message = "";
    }
    if (title == null) {
      title = "";
    }
    helpMessages.put(author, new Messages(title, message));

    if (author.equals(activeAuthor)) {
      helpPanel.setText(message);
      helpPanel.setTitle(title);
    }
  }

  /**
   * Part of public API. Adds more text to existing one.
   * 
   * @param author
   *          - author of message
   * @param message
   */
  public void addHelpMessage(ModelUrl author, String message) {
    Messages existingMessage = helpMessages.get(author);
    if (existingMessage == null) {
      existingMessage = new Messages("", message);
    } else {
      existingMessage = new Messages(existingMessage.getTitle(), existingMessage.getText()
          + message);
    }
    setHelpMessage(author, existingMessage.getTitle(), existingMessage.getText());
  }

  /**
   * Called by WindowsManager when current active object changed
   * 
   * @param url
   *          - new active object
   */
  void setActiveAuthor(ModelUrl url) {
    if (activeAuthor != null) {
      if (activeAuthor.equals(url)) {
        return;
      } else {
        activeAuthor = url;
      }
    } else {
      activeAuthor = url;
    }
    Messages message = helpMessages.get(activeAuthor);

    if (message != null) {
      helpPanel.setText(message.getText());
      helpPanel.setTitle(message.getTitle());
    } else {
      helpPanel.setText("");
      helpPanel.setTitle("");
    }

  }
}
